package com.mq.mqconfig;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启消息强制投递
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("消息数据：" + correlationData);
                if (ack) {
                    System.out.println("消息已到达交换机");
                } else {
                    System.out.println("消息未到达交换机，原因是：" + cause);
                    // 重新发送消息 or 消息入库到消息表
                }
            }
        });


        // 消息回退
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                System.out.println("发送失败的消息内容returned.getMessage() = " + returned.getMessage());
                System.out.println("returned.getReplyCode() = " + returned.getReplyCode());
                System.out.println("returned.getExchange() = " + returned.getExchange());
                System.out.println("returned.getReplyText() = " + returned.getReplyText());
            }
        });

        return rabbitTemplate;
    }
}
